<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
        "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="../Styles/sure3.css" rel="stylesheet" type="text/css"/>
    <link href="../Styles/base1.css" rel="stylesheet" type="text/css"/>
</head>

<body>
<div class="markdown-body entry-content" itemprop="text">
    <h1><a href="#arraybuffer"  class="anchor" id="user-content-arraybuffer">

    </a>ArrayBuffer
    </h1>
    <p><code>ArrayBuffer</code>对象、<code>TypedArray</code>视图和<code>DataView</code>视图是 JavaScript
        操作二进制数据的一个接口。这些对象早就存在，属于独立的规格（2011 年 2 月发布），ES6 将它们纳入了 ECMAScript 规格，并且增加了新的方法。它们都是以数组的语法处理二进制数据，所以统称为二进制数组。</p>
    <p>这个接口的原始设计目的，与 WebGL 项目有关。所谓 WebGL，就是指浏览器与显卡之间的通信接口，为了满足 JavaScript
        与显卡之间大量的、实时的数据交换，它们之间的数据通信必须是二进制的，而不能是传统的文本格式。文本格式传递一个 32 位整数，两端的 JavaScript 脚本与显卡都要进行格式转化，将非常耗时。这时要是存在一种机制，可以像
        C 语言那样，直接操作字节，将 4 个字节的 32 位整数，以二进制形式原封不动地送入显卡，脚本的性能就会大幅提升。</p>
    <p>二进制数组就是在这种背景下诞生的。它很像 C 语言的数组，允许开发者以数组下标的形式，直接操作内存，大大增强了 JavaScript 处理二进制数据的能力，使得开发者有可能通过 JavaScript
        与操作系统的原生接口进行二进制通信。</p>
    <p>二进制数组由三类对象组成。</p>
    <p><strong>（1）<code>ArrayBuffer</code>对象</strong>：代表内存之中的一段二进制数据，可以通过“视图”进行操作。“视图”部署了数组接口，这意味着，可以用数组的方法操作内存。</p>
    <p><strong>（2）<code>TypedArray</code>视图</strong>：共包括 9 种类型的视图，比如<code>Uint8Array</code>（无符号 8 位整数）数组视图, <code>Int16Array</code>（16
        位整数）数组视图, <code>Float32Array</code>（32 位浮点数）数组视图等等。</p>
    <p><strong>（3）<code>DataView</code>视图</strong>：可以自定义复合格式的视图，比如第一个字节是 Uint8（无符号 8 位整数）、第二、三个字节是 Int16（16
        位整数）、第四个字节开始是 Float32（32 位浮点数）等等，此外还可以自定义字节序。</p>
    <p>简单说，<code>ArrayBuffer</code>对象代表原始的二进制数据，TypedArray 视图用来读写简单类型的二进制数据，<code>DataView</code>视图用来读写复杂类型的二进制数据。</p>
    <p>TypedArray 视图支持的数据类型一共有 9 种（<code>DataView</code>视图支持除<code>Uint8C</code>以外的其他 8 种）。</p>
    <table>
        <thead>
        <tr>
            <th>数据类型</th>
            <th>字节长度</th>
            <th>含义</th>
            <th>对应的 C 语言类型</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>Int8</td>
            <td>1</td>
            <td>8 位带符号整数</td>
            <td>signed char</td>
        </tr>
        <tr>
            <td>Uint8</td>
            <td>1</td>
            <td>8 位不带符号整数</td>
            <td>unsigned char</td>
        </tr>
        <tr>
            <td>Uint8C</td>
            <td>1</td>
            <td>8 位不带符号整数（自动过滤溢出）</td>
            <td>unsigned char</td>
        </tr>
        <tr>
            <td>Int16</td>
            <td>2</td>
            <td>16 位带符号整数</td>
            <td>short</td>
        </tr>
        <tr>
            <td>Uint16</td>
            <td>2</td>
            <td>16 位不带符号整数</td>
            <td>unsigned short</td>
        </tr>
        <tr>
            <td>Int32</td>
            <td>4</td>
            <td>32 位带符号整数</td>
            <td>int</td>
        </tr>
        <tr>
            <td>Uint32</td>
            <td>4</td>
            <td>32 位不带符号的整数</td>
            <td>unsigned int</td>
        </tr>
        <tr>
            <td>Float32</td>
            <td>4</td>
            <td>32 位浮点数</td>
            <td>float</td>
        </tr>
        <tr>
            <td>Float64</td>
            <td>8</td>
            <td>64 位浮点数</td>
            <td>double</td>
        </tr>
        </tbody>
    </table>
    <p>注意，二进制数组并不是真正的数组，而是类似数组的对象。</p>
    <p>很多浏览器操作的 API，用到了二进制数组操作二进制数据，下面是其中的几个。</p>
    <ul>
        <li>File API</li>
        <li>XMLHttpRequest</li>
        <li>Fetch API</li>
        <li>Canvas</li>
        <li>WebSockets</li>
    </ul>
    <h2><a href="#arraybuffer-对象"  class="anchor" id="user-content-arraybuffer-对象">

    </a>ArrayBuffer 对象
    </h2>
    <h3><a href="#概述"  class="anchor" id="user-content-概述">

    </a>概述
    </h3>
    <p><code>ArrayBuffer</code>对象代表储存二进制数据的一段内存，它不能直接读写，只能通过视图（<code>TypedArray</code>视图和<code>DataView</code>视图)来读写，视图的作用是以指定格式解读二进制数据。
    </p>
    <p><code>ArrayBuffer</code>也是一个构造函数，可以分配一段可以存放数据的连续内存区域。</p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-k">const</span> <span class="pl-c1">buf</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span class="pl-c1">32</span>);</pre>
    </div>
    <p>上面代码生成了一段 32 字节的内存区域，每个字节的值默认都是 0。可以看到，<code>ArrayBuffer</code>构造函数的参数是所需要的内存大小（单位字节）。</p>
    <p>为了读写这段内容，需要为它指定视图。<code>DataView</code>视图的创建，需要提供<code>ArrayBuffer</code>对象实例作为参数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">buf</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">32</span>);
<span class="pl-k">const</span> <span class="pl-c1">dataView</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">DataView</span>(buf);
<span class="pl-smi">dataView</span>.<span class="pl-en">getUint8</span>(<span class="pl-c1">0</span>) <span
                class="pl-c"><span class="pl-c">//</span> 0</span></pre>
    </div>
    <p>上面代码对一段 32 字节的内存，建立<code>DataView</code>视图，然后以不带符号的 8 位整数格式，从头读取 8 位二进制数据，结果得到 0，因为原始内存的<code>ArrayBuffer</code>对象，默认所有位都是
        0。</p>
    <p>另一种 TypedArray 视图，与<code>DataView</code>视图的一个区别是，它不是一个构造函数，而是一组构造函数，代表不同的数据格式。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">12</span>);

<span class="pl-k">const</span> <span class="pl-c1">x1</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int32Array</span>(buffer);
x1[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">1</span>;
<span class="pl-k">const</span> <span class="pl-c1">x2</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Uint8Array</span>(buffer);
x2[<span class="pl-c1">0</span>]  <span class="pl-k">=</span> <span class="pl-c1">2</span>;

x1[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 2</span></pre>
    </div>
    <p>上面代码对同一段内存，分别建立两种视图：32 位带符号整数（<code>Int32Array</code>构造函数）和 8 位不带符号整数（<code>Uint8Array</code>构造函数）。由于两个视图对应的是同一段内存，一个视图修改底层内存，会影响到另一个视图。
    </p>
    <p>TypedArray 视图的构造函数，除了接受<code>ArrayBuffer</code>实例作为参数，还可以接受普通数组作为参数，直接分配内存生成底层的<code>ArrayBuffer</code>实例，并同时完成对这段内存的赋值。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">typedArray</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
            class="pl-en">Uint8Array</span>([<span class="pl-c1">0</span>,<span class="pl-c1">1</span>,<span
            class="pl-c1">2</span>]);
<span class="pl-smi">typedArray</span>.<span class="pl-c1">length</span> <span class="pl-c"><span class="pl-c">//</span> 3</span>

typedArray[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">5</span>;
typedArray <span class="pl-c"><span class="pl-c">//</span> [5, 1, 2]</span></pre>
    </div>
    <p>上面代码使用 TypedArray 视图的<code>Uint8Array</code>构造函数，新建一个不带符号的 8 位整数视图。可以看到，<code>Uint8Array</code>直接使用普通数组作为参数，对底层内存的赋值同时完成。
    </p>
    <h3><a href="#arraybufferprototypebytelength"  class="anchor"
           id="user-content-arraybufferprototypebytelength">

    </a>ArrayBuffer.prototype.byteLength
    </h3>
    <p><code>ArrayBuffer</code>实例的<code>byteLength</code>属性，返回所分配的内存区域的字节长度。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">32</span>);
<span class="pl-smi">buffer</span>.<span class="pl-smi">byteLength</span>
<span class="pl-c"><span class="pl-c">//</span> 32</span></pre>
    </div>
    <p>如果要分配的内存区域很大，有可能分配失败（因为没有那么多的连续空余内存），所以有必要检查是否分配成功。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">if</span> (<span
            class="pl-smi">buffer</span>.<span class="pl-smi">byteLength</span> <span class="pl-k">===</span> n) {
  <span class="pl-c"><span class="pl-c">//</span> 成功</span>
} <span class="pl-k">else</span> {
  <span class="pl-c"><span class="pl-c">//</span> 失败</span>
}</pre>
    </div>
    <h3><a href="#arraybufferprototypeslice"  class="anchor"
           id="user-content-arraybufferprototypeslice">

    </a>ArrayBuffer.prototype.slice()
    </h3>
    <p><code>ArrayBuffer</code>实例有一个<code>slice</code>方法，允许将内存区域的一部分，拷贝生成一个新的<code>ArrayBuffer</code>对象。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">8</span>);
<span class="pl-k">const</span> <span class="pl-c1">newBuffer</span> <span class="pl-k">=</span> <span class="pl-smi">buffer</span>.<span
                class="pl-c1">slice</span>(<span class="pl-c1">0</span>, <span class="pl-c1">3</span>);</pre>
    </div>
    <p>上面代码拷贝<code>buffer</code>对象的前 3 个字节（从 0 开始，到第 3 个字节前面结束），生成一个新的<code>ArrayBuffer</code>对象。<code>slice</code>方法其实包含两步，第一步是先分配一段新内存，第二步是将原来那个<code>ArrayBuffer</code>对象拷贝过去。
    </p>
    <p><code>slice</code>方法接受两个参数，第一个参数表示拷贝开始的字节序号（含该字节），第二个参数表示拷贝截止的字节序号（不含该字节）。如果省略第二个参数，则默认到原<code>ArrayBuffer</code>对象的结尾。
    </p>
    <p>除了<code>slice</code>方法，<code>ArrayBuffer</code>对象不提供任何直接读写内存的方法，只允许在其上方建立视图，然后通过视图读写。</p>
    <h3><a href="#arraybufferisview"  class="anchor" id="user-content-arraybufferisview">

    </a>ArrayBuffer.isView()
    </h3>
    <p><code>ArrayBuffer</code>有一个静态方法<code>isView</code>，返回一个布尔值，表示参数是否为<code>ArrayBuffer</code>的视图实例。这个方法大致相当于判断参数，是否为
        TypedArray 实例或<code>DataView</code>实例。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">8</span>);
<span class="pl-c1">ArrayBuffer</span>.<span class="pl-en">isView</span>(buffer) <span class="pl-c"><span class="pl-c">//</span> false</span>

<span class="pl-k">const</span> <span class="pl-c1">v</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Int32Array</span>(buffer);
<span class="pl-c1">ArrayBuffer</span>.<span class="pl-en">isView</span>(v) <span class="pl-c"><span
                class="pl-c">//</span> true</span></pre>
    </div>
    <h2><a href="#typedarray-视图"  class="anchor" id="user-content-typedarray-视图">

    </a>TypedArray 视图
    </h2>
    <h3><a href="#概述-1"  class="anchor" id="user-content-概述-1">

    </a>概述
    </h3>
    <p><code>ArrayBuffer</code>对象作为内存区域，可以存放多种类型的数据。同一段内存，不同数据有不同的解读方式，这就叫做“视图”（view）。<code>ArrayBuffer</code>有两种视图，一种是
        TypedArray 视图，另一种是<code>DataView</code>视图。前者的数组成员都是同一个数据类型，后者的数组成员可以是不同的数据类型。</p>
    <p>目前，TypedArray 视图一共包括 9 种类型，每一种视图都是一种构造函数。</p>
    <ul>
        <li><strong><code>Int8Array</code></strong>：8 位有符号整数，长度 1 个字节。</li>
        <li><strong><code>Uint8Array</code></strong>：8 位无符号整数，长度 1 个字节。</li>
        <li><strong><code>Uint8ClampedArray</code></strong>：8 位无符号整数，长度 1 个字节，溢出处理不同。</li>
        <li><strong><code>Int16Array</code></strong>：16 位有符号整数，长度 2 个字节。</li>
        <li><strong><code>Uint16Array</code></strong>：16 位无符号整数，长度 2 个字节。</li>
        <li><strong><code>Int32Array</code></strong>：32 位有符号整数，长度 4 个字节。</li>
        <li><strong><code>Uint32Array</code></strong>：32 位无符号整数，长度 4 个字节。</li>
        <li><strong><code>Float32Array</code></strong>：32 位浮点数，长度 4 个字节。</li>
        <li><strong><code>Float64Array</code></strong>：64 位浮点数，长度 8 个字节。</li>
    </ul>
    <p>这 9 个构造函数生成的数组，统称为 TypedArray 视图。它们很像普通数组，都有<code>length</code>属性，都能用方括号运算符（<code>[]</code>）获取单个元素，所有数组的方法，在它们上面都能使用。普通数组与
        TypedArray 数组的差异主要在以下方面。</p>
    <ul>
        <li>TypedArray 数组的所有成员，都是同一种类型。</li>
        <li>TypedArray 数组的成员是连续的，不会有空位。</li>
        <li>TypedArray 数组成员的默认值为 0。比如，<code>new Array(10)</code>返回一个普通数组，里面没有任何成员，只是 10 个空位；<code>new
            Uint8Array(10)</code>返回一个 TypedArray 数组，里面 10 个成员都是 0。
        </li>
        <li>TypedArray 数组只是一层视图，本身不储存数据，它的数据都储存在底层的<code>ArrayBuffer</code>对象之中，要获取底层对象必须使用<code>buffer</code>属性。</li>
    </ul>
    <h3><a href="#构造函数"  class="anchor" id="user-content-构造函数">

    </a>构造函数
    </h3>
    <p>TypedArray 数组提供 9 种构造函数，用来生成相应类型的数组实例。</p>
    <p>构造函数有多种用法。</p>
    <p><strong>（1）TypedArray(buffer, byteOffset=0, length?)</strong></p>
    <p>同一个<code>ArrayBuffer</code>对象之上，可以根据不同的数据类型，建立多个视图。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 创建一个8字节的ArrayBuffer</span>
<span class="pl-k">const</span> <span class="pl-c1">b</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span class="pl-c1">8</span>);

<span class="pl-c"><span class="pl-c">//</span> 创建一个指向b的Int32视图，开始于字节0，直到缓冲区的末尾</span>
<span class="pl-k">const</span> <span class="pl-c1">v1</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int32Array</span>(b);

<span class="pl-c"><span class="pl-c">//</span> 创建一个指向b的Uint8视图，开始于字节2，直到缓冲区的末尾</span>
<span class="pl-k">const</span> <span class="pl-c1">v2</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Uint8Array</span>(b, <span class="pl-c1">2</span>);

<span class="pl-c"><span class="pl-c">//</span> 创建一个指向b的Int16视图，开始于字节2，长度为2</span>
<span class="pl-k">const</span> <span class="pl-c1">v3</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int16Array</span>(b, <span class="pl-c1">2</span>, <span class="pl-c1">2</span>);</pre>
    </div>
    <p>上面代码在一段长度为 8 个字节的内存（<code>b</code>）之上，生成了三个视图：<code>v1</code>、<code>v2</code>和<code>v3</code>。</p>
    <p>视图的构造函数可以接受三个参数：</p>
    <ul>
        <li>第一个参数（必需）：视图对应的底层<code>ArrayBuffer</code>对象。</li>
        <li>第二个参数（可选）：视图开始的字节序号，默认从 0 开始。</li>
        <li>第三个参数（可选）：视图包含的数据个数，默认直到本段内存区域结束。</li>
    </ul>
    <p>因此，<code>v1</code>、<code>v2</code>和<code>v3</code>是重叠的：<code>v1[0]</code>是一个 32 位整数，指向字节 0 ～字节
        3；<code>v2[0]</code>是一个 8 位无符号整数，指向字节 2；<code>v3[0]</code>是一个 16 位整数，指向字节 2 ～字节
        3。只要任何一个视图对内存有所修改，就会在另外两个视图上反应出来。</p>
    <p>注意，<code>byteOffset</code>必须与所要建立的数据类型一致，否则会报错。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">8</span>);
<span class="pl-k">const</span> <span class="pl-c1">i16</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int16Array</span>(buffer, <span class="pl-c1">1</span>);
<span class="pl-c"><span class="pl-c">//</span> Uncaught RangeError: start offset of Int16Array should be a multiple of 2</span></pre>
    </div>
    <p>上面代码中，新生成一个 8 个字节的<code>ArrayBuffer</code>对象，然后在这个对象的第一个字节，建立带符号的 16 位整数视图，结果报错。因为，带符号的 16 位整数需要两个字节，所以<code>byteOffset</code>参数必须能够被
        2 整除。</p>
    <p>如果想从任意字节开始解读<code>ArrayBuffer</code>对象，必须使用<code>DataView</code>视图，因为 TypedArray 视图只提供 9 种固定的解读格式。</p>
    <p><strong>（2）TypedArray(length)</strong></p>
    <p>视图还可以不通过<code>ArrayBuffer</code>对象，直接分配内存而生成。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">f64a</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Float64Array</span>(<span
            class="pl-c1">8</span>);
f64a[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">10</span>;
f64a[<span class="pl-c1">1</span>] <span class="pl-k">=</span> <span class="pl-c1">20</span>;
f64a[<span class="pl-c1">2</span>] <span class="pl-k">=</span> f64a[<span class="pl-c1">0</span>] <span
                class="pl-k">+</span> f64a[<span class="pl-c1">1</span>];</pre>
    </div>
    <p>上面代码生成一个 8 个成员的<code>Float64Array</code>数组（共 64 字节），然后依次对每个成员赋值。这时，视图构造函数的参数就是成员的个数。可以看到，视图数组的赋值操作与普通数组的操作毫无两样。
    </p>
    <p><strong>（3）TypedArray(typedArray)</strong></p>
    <p>TypedArray 数组的构造函数，可以接受另一个 TypedArray 实例作为参数。</p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-k">const</span> <span class="pl-c1">typedArray</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Int8Array</span>(<span class="pl-k">new</span> <span
                class="pl-en">Uint8Array</span>(<span class="pl-c1">4</span>));</pre>
    </div>
    <p>上面代码中，<code>Int8Array</code>构造函数接受一个<code>Uint8Array</code>实例作为参数。</p>
    <p>注意，此时生成的新数组，只是复制了参数数组的值，对应的底层内存是不一样的。新数组会开辟一段新的内存储存数据，不会在原数组的内存之上建立视图。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">x</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Int8Array</span>([<span
            class="pl-c1">1</span>, <span class="pl-c1">1</span>]);
<span class="pl-k">const</span> <span class="pl-c1">y</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Int8Array</span>(x);
x[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 1</span>
y[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 1</span>

x[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">2</span>;
y[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 1</span></pre>
    </div>
    <p>上面代码中，数组<code>y</code>是以数组<code>x</code>为模板而生成的，当<code>x</code>变动的时候，<code>y</code>并没有变动。</p>
    <p>如果想基于同一段内存，构造不同的视图，可以采用下面的写法。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">x</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Int8Array</span>([<span
            class="pl-c1">1</span>, <span class="pl-c1">1</span>]);
<span class="pl-k">const</span> <span class="pl-c1">y</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Int8Array</span>(<span class="pl-smi">x</span>.<span
                class="pl-smi">buffer</span>);
x[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 1</span>
y[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 1</span>

x[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">2</span>;
y[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 2</span></pre>
    </div>
    <p><strong>（4）TypedArray(arrayLikeObject)</strong></p>
    <p>构造函数的参数也可以是一个普通数组，然后直接生成 TypedArray 实例。</p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-k">const</span> <span class="pl-c1">typedArray</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint8Array</span>([<span class="pl-c1">1</span>, <span
                class="pl-c1">2</span>, <span class="pl-c1">3</span>, <span class="pl-c1">4</span>]);</pre>
    </div>
    <p>注意，这时 TypedArray 视图会重新开辟内存，不会在原数组的内存上建立视图。</p>
    <p>上面代码从一个普通的数组，生成一个 8 位无符号整数的 TypedArray 实例。</p>
    <p>TypedArray 数组也可以转换回普通数组。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">normalArray</span> <span class="pl-k">=</span> [<span class="pl-k">...</span>typedArray];
<span class="pl-c"><span class="pl-c">//</span> or</span>
<span class="pl-k">const</span> <span class="pl-c1">normalArray</span> <span class="pl-k">=</span> <span class="pl-c1">Array</span>.<span
                class="pl-en">from</span>(typedArray);
<span class="pl-c"><span class="pl-c">//</span> or</span>
<span class="pl-k">const</span> <span class="pl-c1">normalArray</span> <span class="pl-k">=</span> <span class="pl-c1">Array</span>.<span
                class="pl-c1">prototype</span>.<span class="pl-smi">slice</span>.<span class="pl-c1">call</span>(typedArray);</pre>
    </div>
    <h3><a href="#数组方法"  class="anchor" id="user-content-数组方法">

    </a>数组方法
    </h3>
    <p>普通数组的操作方法和属性，对 TypedArray 数组完全适用。</p>
    <ul>
        <li><code>TypedArray.prototype.copyWithin(target, start[, end = this.length])</code></li>
        <li><code>TypedArray.prototype.entries()</code></li>
        <li><code>TypedArray.prototype.every(callbackfn, thisArg?)</code></li>
        <li><code>TypedArray.prototype.fill(value, start=0, end=this.length)</code></li>
        <li><code>TypedArray.prototype.filter(callbackfn, thisArg?)</code></li>
        <li><code>TypedArray.prototype.find(predicate, thisArg?)</code></li>
        <li><code>TypedArray.prototype.findIndex(predicate, thisArg?)</code></li>
        <li><code>TypedArray.prototype.forEach(callbackfn, thisArg?)</code></li>
        <li><code>TypedArray.prototype.indexOf(searchElement, fromIndex=0)</code></li>
        <li><code>TypedArray.prototype.join(separator)</code></li>
        <li><code>TypedArray.prototype.keys()</code></li>
        <li><code>TypedArray.prototype.lastIndexOf(searchElement, fromIndex?)</code></li>
        <li><code>TypedArray.prototype.map(callbackfn, thisArg?)</code></li>
        <li><code>TypedArray.prototype.reduce(callbackfn, initialValue?)</code></li>
        <li><code>TypedArray.prototype.reduceRight(callbackfn, initialValue?)</code></li>
        <li><code>TypedArray.prototype.reverse()</code></li>
        <li><code>TypedArray.prototype.slice(start=0, end=this.length)</code></li>
        <li><code>TypedArray.prototype.some(callbackfn, thisArg?)</code></li>
        <li><code>TypedArray.prototype.sort(comparefn)</code></li>
        <li><code>TypedArray.prototype.toLocaleString(reserved1?, reserved2?)</code></li>
        <li><code>TypedArray.prototype.toString()</code></li>
        <li><code>TypedArray.prototype.values()</code></li>
    </ul>
    <p>上面所有方法的用法，请参阅数组方法的介绍，这里不再重复了。</p>
    <p>注意，TypedArray 数组没有<code>concat</code>方法。如果想要合并多个 TypedArray 数组，可以用下面这个函数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span> <span
            class="pl-en">concatenate</span>(<span class="pl-smi">resultConstructor</span>, <span
            class="pl-k">...</span><span class="pl-v">arrays</span>) {
  <span class="pl-k">let</span> totalLength <span class="pl-k">=</span> <span class="pl-c1">0</span>;
  <span class="pl-k">for</span> (<span class="pl-k">let</span> arr <span class="pl-k">of</span> arrays) {
    totalLength <span class="pl-k">+=</span> <span class="pl-smi">arr</span>.<span class="pl-c1">length</span>;
  }
  <span class="pl-k">let</span> result <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">resultConstructor</span>(totalLength);
  <span class="pl-k">let</span> offset <span class="pl-k">=</span> <span class="pl-c1">0</span>;
  <span class="pl-k">for</span> (<span class="pl-k">let</span> arr <span class="pl-k">of</span> arrays) {
    <span class="pl-smi">result</span>.<span class="pl-c1">set</span>(arr, offset);
    offset <span class="pl-k">+=</span> <span class="pl-smi">arr</span>.<span class="pl-c1">length</span>;
  }
  <span class="pl-k">return</span> result;
}

<span class="pl-en">concatenate</span>(<span class="pl-c1">Uint8Array</span>, <span
                class="pl-c1">Uint8Array</span>.<span class="pl-en">of</span>(<span class="pl-c1">1</span>, <span
                class="pl-c1">2</span>), <span class="pl-c1">Uint8Array</span>.<span class="pl-en">of</span>(<span
                class="pl-c1">3</span>, <span class="pl-c1">4</span>))
<span class="pl-c"><span class="pl-c">//</span> Uint8Array [1, 2, 3, 4]</span></pre>
    </div>
    <p>另外，TypedArray 数组与普通数组一样，部署了 Iterator 接口，所以可以被遍历。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> ui8 <span class="pl-k">=</span> <span
            class="pl-c1">Uint8Array</span>.<span class="pl-en">of</span>(<span class="pl-c1">0</span>, <span
            class="pl-c1">1</span>, <span class="pl-c1">2</span>);
<span class="pl-k">for</span> (<span class="pl-k">let</span> byte <span class="pl-k">of</span> ui8) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(byte);
}
<span class="pl-c"><span class="pl-c">//</span> 0</span>
<span class="pl-c"><span class="pl-c">//</span> 1</span>
<span class="pl-c"><span class="pl-c">//</span> 2</span></pre>
    </div>
    <h3><a href="#字节序"  class="anchor" id="user-content-字节序">

    </a>字节序
    </h3>
    <p>字节序指的是数值在内存中的表示方式。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">16</span>);
<span class="pl-k">const</span> <span class="pl-c1">int32View</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Int32Array</span>(buffer);

<span class="pl-k">for</span> (<span class="pl-k">let</span> i <span class="pl-k">=</span> <span class="pl-c1">0</span>; i <span
                class="pl-k">&lt;</span> <span class="pl-smi">int32View</span>.<span class="pl-c1">length</span>; i<span
                class="pl-k">++</span>) {
  int32View[i] <span class="pl-k">=</span> i <span class="pl-k">*</span> <span class="pl-c1">2</span>;
}</pre>
    </div>
    <p>上面代码生成一个 16 字节的<code>ArrayBuffer</code>对象，然后在它的基础上，建立了一个 32 位整数的视图。由于每个 32 位整数占据 4 个字节，所以一共可以写入 4 个整数，依次为
        0，2，4，6。</p>
    <p>如果在这段数据上接着建立一个 16 位整数的视图，则可以读出完全不一样的结果。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">int16View</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Int16Array</span>(buffer);

<span class="pl-k">for</span> (<span class="pl-k">let</span> i <span class="pl-k">=</span> <span class="pl-c1">0</span>; i <span
                class="pl-k">&lt;</span> <span class="pl-smi">int16View</span>.<span class="pl-c1">length</span>; i<span
                class="pl-k">++</span>) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">"</span>Entry <span
                class="pl-pds">"</span></span> <span class="pl-k">+</span> i <span class="pl-k">+</span> <span
                class="pl-s"><span class="pl-pds">"</span>: <span class="pl-pds">"</span></span> <span
                class="pl-k">+</span> int16View[i]);
}
<span class="pl-c"><span class="pl-c">//</span> Entry 0: 0</span>
<span class="pl-c"><span class="pl-c">//</span> Entry 1: 0</span>
<span class="pl-c"><span class="pl-c">//</span> Entry 2: 2</span>
<span class="pl-c"><span class="pl-c">//</span> Entry 3: 0</span>
<span class="pl-c"><span class="pl-c">//</span> Entry 4: 4</span>
<span class="pl-c"><span class="pl-c">//</span> Entry 5: 0</span>
<span class="pl-c"><span class="pl-c">//</span> Entry 6: 6</span>
<span class="pl-c"><span class="pl-c">//</span> Entry 7: 0</span></pre>
    </div>
    <p>由于每个 16 位整数占据 2 个字节，所以整个<code>ArrayBuffer</code>对象现在分成 8 段。然后，由于 x86 体系的计算机都采用小端字节序（little
        endian），相对重要的字节排在后面的内存地址，相对不重要字节排在前面的内存地址，所以就得到了上面的结果。</p>
    <p>比如，一个占据四个字节的 16
        进制数<code>0x12345678</code>，决定其大小的最重要的字节是“12”，最不重要的是“78”。小端字节序将最不重要的字节排在前面，储存顺序就是<code>78563412</code>；大端字节序则完全相反，将最重要的字节排在前面，储存顺序就是<code>12345678</code>。目前，所有个人电脑几乎都是小端字节序，所以
        TypedArray 数组内部也采用小端字节序读写数据，或者更准确的说，按照本机操作系统设定的字节序读写数据。</p>
    <p>这并不意味大端字节序不重要，事实上，很多网络设备和特定的操作系统采用的是大端字节序。这就带来一个严重的问题：如果一段数据是大端字节序，TypedArray
        数组将无法正确解析，因为它只能处理小端字节序！为了解决这个问题，JavaScript 引入<code>DataView</code>对象，可以设定字节序，下文会详细介绍。</p>
    <p>下面是另一个例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 假定某段buffer包含如下字节 [0x02, 0x01, 0x03, 0x07]</span>
<span class="pl-k">const</span> <span class="pl-c1">buffer</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span class="pl-c1">4</span>);
<span class="pl-k">const</span> <span class="pl-c1">v1</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Uint8Array</span>(buffer);
v1[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">2</span>;
v1[<span class="pl-c1">1</span>] <span class="pl-k">=</span> <span class="pl-c1">1</span>;
v1[<span class="pl-c1">2</span>] <span class="pl-k">=</span> <span class="pl-c1">3</span>;
v1[<span class="pl-c1">3</span>] <span class="pl-k">=</span> <span class="pl-c1">7</span>;

<span class="pl-k">const</span> <span class="pl-c1">uInt16View</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint16Array</span>(buffer);

<span class="pl-c"><span class="pl-c">//</span> 计算机采用小端字节序</span>
<span class="pl-c"><span class="pl-c">//</span> 所以头两个字节等于258</span>
<span class="pl-k">if</span> (uInt16View[<span class="pl-c1">0</span>] <span class="pl-k">===</span> <span
                class="pl-c1">258</span>) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span
                class="pl-pds">'</span>OK<span class="pl-pds">'</span></span>); <span class="pl-c"><span
                class="pl-c">//</span> "OK"</span>
}

<span class="pl-c"><span class="pl-c">//</span> 赋值运算</span>
uInt16View[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">255</span>;    <span
                class="pl-c"><span class="pl-c">//</span> 字节变为[0xFF, 0x00, 0x03, 0x07]</span>
uInt16View[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">0xff05</span>; <span
                class="pl-c"><span class="pl-c">//</span> 字节变为[0x05, 0xFF, 0x03, 0x07]</span>
uInt16View[<span class="pl-c1">1</span>] <span class="pl-k">=</span> <span class="pl-c1">0x0210</span>; <span
                class="pl-c"><span class="pl-c">//</span> 字节变为[0x05, 0xFF, 0x10, 0x02]</span></pre>
    </div>
    <p>下面的函数可以用来判断，当前视图是小端字节序，还是大端字节序。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">BIG_ENDIAN</span> <span class="pl-k">=</span> <span class="pl-c1">Symbol</span>(<span
            class="pl-s"><span class="pl-pds">'</span>BIG_ENDIAN<span class="pl-pds">'</span></span>);
<span class="pl-k">const</span> <span class="pl-c1">LITTLE_ENDIAN</span> <span class="pl-k">=</span> <span
                class="pl-c1">Symbol</span>(<span class="pl-s"><span class="pl-pds">'</span>LITTLE_ENDIAN<span
                class="pl-pds">'</span></span>);

<span class="pl-k">function</span> <span class="pl-en">getPlatformEndianness</span>() {
  <span class="pl-k">let</span> arr32 <span class="pl-k">=</span> <span class="pl-c1">Uint32Array</span>.<span
                class="pl-en">of</span>(<span class="pl-c1">0x12345678</span>);
  <span class="pl-k">let</span> arr8 <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Uint8Array</span>(<span
                class="pl-smi">arr32</span>.<span class="pl-smi">buffer</span>);
  <span class="pl-k">switch</span> ((arr8[<span class="pl-c1">0</span>]<span class="pl-k">*</span><span class="pl-c1">0x1000000</span>) <span
                class="pl-k">+</span> (arr8[<span class="pl-c1">1</span>]<span class="pl-k">*</span><span class="pl-c1">0x10000</span>) <span
                class="pl-k">+</span> (arr8[<span class="pl-c1">2</span>]<span class="pl-k">*</span><span class="pl-c1">0x100</span>) <span
                class="pl-k">+</span> (arr8[<span class="pl-c1">3</span>])) {
    <span class="pl-k">case</span> <span class="pl-c1">0x12345678</span>:
      <span class="pl-k">return</span> <span class="pl-c1">BIG_ENDIAN</span>;
    <span class="pl-k">case</span> <span class="pl-c1">0x78563412</span>:
      <span class="pl-k">return</span> <span class="pl-c1">LITTLE_ENDIAN</span>;
    <span class="pl-k">default</span>:
      <span class="pl-k">throw</span> <span class="pl-k">new</span> <span class="pl-en">Error</span>(<span class="pl-s"><span
                class="pl-pds">'</span>Unknown endianness<span class="pl-pds">'</span></span>);
  }
}</pre>
    </div>
    <p>总之，与普通数组相比，TypedArray 数组的最大优点就是可以直接操作内存，不需要数据类型转换，所以速度快得多。</p>
    <h3><a href="#bytes_per_element-属性"  class="anchor" id="user-content-bytes_per_element-属性">

    </a>BYTES_PER_ELEMENT 属性
    </h3>
    <p>每一种视图的构造函数，都有一个<code>BYTES_PER_ELEMENT</code>属性，表示这种数据类型占据的字节数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c1">Int8Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span
            class="pl-c"><span class="pl-c">//</span> 1</span>
<span class="pl-c1">Uint8Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span class="pl-c"><span
                class="pl-c">//</span> 1</span>
<span class="pl-c1">Int16Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span class="pl-c"><span
                class="pl-c">//</span> 2</span>
<span class="pl-c1">Uint16Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span class="pl-c"><span
                class="pl-c">//</span> 2</span>
<span class="pl-c1">Int32Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span class="pl-c"><span
                class="pl-c">//</span> 4</span>
<span class="pl-c1">Uint32Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span class="pl-c"><span
                class="pl-c">//</span> 4</span>
<span class="pl-c1">Float32Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span class="pl-c"><span
                class="pl-c">//</span> 4</span>
<span class="pl-c1">Float64Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span class="pl-c"><span
                class="pl-c">//</span> 8</span></pre>
    </div>
    <p>这个属性在 TypedArray 实例上也能获取，即有<code>TypedArray.prototype.BYTES_PER_ELEMENT</code>。</p>
    <h3><a href="#arraybuffer-与字符串的互相转换"  class="anchor" id="user-content-arraybuffer-与字符串的互相转换">

    </a>ArrayBuffer 与字符串的互相转换
    </h3>
    <p><code>ArrayBuffer</code>转为字符串，或者字符串转为<code>ArrayBuffer</code>，有一个前提，即字符串的编码方法是确定的。假定字符串采用 UTF-16 编码（JavaScript
        的内部编码方式），可以自己编写转换函数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> ArrayBuffer 转为字符串，参数为 ArrayBuffer 对象</span>
<span class="pl-k">function</span> <span class="pl-en">ab2str</span>(<span class="pl-smi">buf</span>) {
  <span class="pl-c"><span class="pl-c">//</span> 注意，如果是大型二进制数组，为了避免溢出，</span>
  <span class="pl-c"><span class="pl-c">//</span> 必须一个一个字符地转</span>
  <span class="pl-k">return</span> <span class="pl-c1">String</span>.<span class="pl-smi">fromCharCode</span>.<span
                class="pl-c1">apply</span>(<span class="pl-c1">null</span>, <span class="pl-k">new</span> <span
                class="pl-en">Uint16Array</span>(buf));
}

<span class="pl-c"><span class="pl-c">//</span> 字符串转为 ArrayBuffer 对象，参数为字符串</span>
<span class="pl-k">function</span> <span class="pl-en">str2ab</span>(<span class="pl-smi">str</span>) {
  <span class="pl-k">const</span> <span class="pl-c1">buf</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span class="pl-smi">str</span>.<span
                class="pl-c1">length</span> <span class="pl-k">*</span> <span class="pl-c1">2</span>); <span
                class="pl-c"><span class="pl-c">//</span> 每个字符占用2个字节</span>
  <span class="pl-k">const</span> <span class="pl-c1">bufView</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint16Array</span>(buf);
  <span class="pl-k">for</span> (<span class="pl-k">let</span> i <span class="pl-k">=</span> <span
                class="pl-c1">0</span>, strLen <span class="pl-k">=</span> <span class="pl-smi">str</span>.<span
                class="pl-c1">length</span>; i <span class="pl-k">&lt;</span> strLen; i<span class="pl-k">++</span>) {
    bufView[i] <span class="pl-k">=</span> <span class="pl-smi">str</span>.<span class="pl-c1">charCodeAt</span>(i);
  }
  <span class="pl-k">return</span> buf;
}</pre>
    </div>
    <h3><a href="#溢出"  class="anchor" id="user-content-溢出">

    </a>溢出
    </h3>
    <p>不同的视图类型，所能容纳的数值范围是确定的。超出这个范围，就会出现溢出。比如，8 位视图只能容纳一个 8 位的二进制值，如果放入一个 9 位的值，就会溢出。</p>
    <p>TypedArray 数组的溢出处理规则，简单来说，就是抛弃溢出的位，然后按照视图类型进行解释。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">uint8</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Uint8Array</span>(<span
            class="pl-c1">1</span>);

uint8[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">256</span>;
uint8[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 0</span>

uint8[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-k">-</span><span class="pl-c1">1</span>;
uint8[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 255</span></pre>
    </div>
    <p>上面代码中，<code>uint8</code>是一个 8 位视图，而 256 的二进制形式是一个 9 位的值<code>100000000</code>，这时就会发生溢出。根据规则，只会保留后 8 位，即<code>00000000</code>。<code>uint8</code>视图的解释规则是无符号的
        8 位整数，所以<code>00000000</code>就是<code>0</code>。</p>
    <p>负数在计算机内部采用“2 的补码”表示，也就是说，将对应的正数值进行否运算，然后加<code>1</code>。比如，<code>-1</code>对应的正值是<code>1</code>，进行否运算以后，得到<code>11111110</code>，再加上<code>1</code>就是补码形式<code>11111111</code>。<code>uint8</code>按照无符号的
        8 位整数解释<code>11111111</code>，返回结果就是<code>255</code>。</p>
    <p>一个简单转换规则，可以这样表示。</p>
    <ul>
        <li>正向溢出（overflow）：当输入值大于当前数据类型的最大值，结果等于当前数据类型的最小值加上余值，再减去 1。</li>
        <li>负向溢出（underflow）：当输入值小于当前数据类型的最小值，结果等于当前数据类型的最大值减去余值，再加上 1。</li>
    </ul>
    <p>上面的“余值”就是模运算的结果，即 JavaScript 里面的<code>%</code>运算符的结果。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c1">12</span> <span class="pl-k">%</span> <span
            class="pl-c1">4</span> <span class="pl-c"><span class="pl-c">//</span> 0</span>
<span class="pl-c1">12</span> <span class="pl-k">%</span> <span class="pl-c1">5</span> <span class="pl-c"><span
                class="pl-c">//</span> 2</span></pre>
    </div>
    <p>上面代码中，12 除以 4 是没有余值的，而除以 5 会得到余值 2。</p>
    <p>请看下面的例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">int8</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Int8Array</span>(<span
            class="pl-c1">1</span>);

int8[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">128</span>;
int8[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> -128</span>

int8[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-k">-</span><span class="pl-c1">129</span>;
int8[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 127</span></pre>
    </div>
    <p>上面例子中，<code>int8</code>是一个带符号的 8 位整数视图，它的最大值是 127，最小值是-128。输入值为<code>128</code>时，相当于正向溢出<code>1</code>，根据“最小值加上余值（128
        除以 127 的余值是 1），再减去 1”的规则，就会返回<code>-128</code>；输入值为<code>-129</code>时，相当于负向溢出<code>1</code>，根据“最大值减去余值（-129
        除以-128 的余值是 1），再加上 1”的规则，就会返回<code>127</code>。</p>
    <p><code>Uint8ClampedArray</code>视图的溢出规则，与上面的规则不同。它规定，凡是发生正向溢出，该值一律等于当前数据类型的最大值，即 255；如果发生负向溢出，该值一律等于当前数据类型的最小值，即 0。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">uint8c</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Uint8ClampedArray</span>(<span
            class="pl-c1">1</span>);

uint8c[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">256</span>;
uint8c[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 255</span>

uint8c[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-k">-</span><span class="pl-c1">1</span>;
uint8c[<span class="pl-c1">0</span>] <span class="pl-c"><span class="pl-c">//</span> 0</span></pre>
    </div>
    <p>上面例子中，<code>uint8C</code>是一个<code>Uint8ClampedArray</code>视图，正向溢出时都返回 255，负向溢出都返回 0。</p>
    <h3><a href="#typedarrayprototypebuffer"  class="anchor"
           id="user-content-typedarrayprototypebuffer">

    </a>TypedArray.prototype.buffer
    </h3>
    <p>TypedArray 实例的<code>buffer</code>属性，返回整段内存区域对应的<code>ArrayBuffer</code>对象。该属性为只读属性。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">a</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Float32Array</span>(<span
            class="pl-c1">64</span>);
<span class="pl-k">const</span> <span class="pl-c1">b</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint8Array</span>(<span class="pl-smi">a</span>.<span
                class="pl-smi">buffer</span>);</pre>
    </div>
    <p>上面代码的<code>a</code>视图对象和<code>b</code>视图对象，对应同一个<code>ArrayBuffer</code>对象，即同一段内存。</p>
    <h3><a href="#typedarrayprototypebytelengthtypedarrayprototypebyteoffset"  class="anchor"
           id="user-content-typedarrayprototypebytelengthtypedarrayprototypebyteoffset">

    </a>TypedArray.prototype.byteLength，TypedArray.prototype.byteOffset
    </h3>
    <p><code>byteLength</code>属性返回 TypedArray 数组占据的内存长度，单位为字节。<code>byteOffset</code>属性返回 TypedArray 数组从底层<code>ArrayBuffer</code>对象的哪个字节开始。这两个属性都是只读属性。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">b</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">8</span>);

<span class="pl-k">const</span> <span class="pl-c1">v1</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int32Array</span>(b);
<span class="pl-k">const</span> <span class="pl-c1">v2</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Uint8Array</span>(b, <span class="pl-c1">2</span>);
<span class="pl-k">const</span> <span class="pl-c1">v3</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int16Array</span>(b, <span class="pl-c1">2</span>, <span class="pl-c1">2</span>);

<span class="pl-smi">v1</span>.<span class="pl-smi">byteLength</span> <span class="pl-c"><span class="pl-c">//</span> 8</span>
<span class="pl-smi">v2</span>.<span class="pl-smi">byteLength</span> <span class="pl-c"><span class="pl-c">//</span> 6</span>
<span class="pl-smi">v3</span>.<span class="pl-smi">byteLength</span> <span class="pl-c"><span class="pl-c">//</span> 4</span>

<span class="pl-smi">v1</span>.<span class="pl-smi">byteOffset</span> <span class="pl-c"><span class="pl-c">//</span> 0</span>
<span class="pl-smi">v2</span>.<span class="pl-smi">byteOffset</span> <span class="pl-c"><span class="pl-c">//</span> 2</span>
<span class="pl-smi">v3</span>.<span class="pl-smi">byteOffset</span> <span class="pl-c"><span class="pl-c">//</span> 2</span></pre>
    </div>
    <h3><a href="#typedarrayprototypelength"  class="anchor"
           id="user-content-typedarrayprototypelength">

    </a>TypedArray.prototype.length
    </h3>
    <p><code>length</code>属性表示 TypedArray 数组含有多少个成员。注意将<code>byteLength</code>属性和<code>length</code>属性区分，前者是字节长度，后者是成员长度。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">a</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Int16Array</span>(<span
            class="pl-c1">8</span>);

<span class="pl-smi">a</span>.<span class="pl-c1">length</span> <span class="pl-c"><span class="pl-c">//</span> 8</span>
<span class="pl-smi">a</span>.<span class="pl-smi">byteLength</span> <span class="pl-c"><span class="pl-c">//</span> 16</span></pre>
    </div>
    <h3><a href="#typedarrayprototypeset"  class="anchor" id="user-content-typedarrayprototypeset">

    </a>TypedArray.prototype.set()
    </h3>
    <p>TypedArray 数组的<code>set</code>方法用于复制数组（普通数组或 TypedArray 数组），也就是将一段内容完全复制到另一段内存。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">a</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Uint8Array</span>(<span
            class="pl-c1">8</span>);
<span class="pl-k">const</span> <span class="pl-c1">b</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint8Array</span>(<span class="pl-c1">8</span>);

<span class="pl-smi">b</span>.<span class="pl-c1">set</span>(a);</pre>
    </div>
    <p>上面代码复制<code>a</code>数组的内容到<code>b</code>数组，它是整段内存的复制，比一个个拷贝成员的那种复制快得多。</p>
    <p><code>set</code>方法还可以接受第二个参数，表示从<code>b</code>对象的哪一个成员开始复制<code>a</code>对象。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">a</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Uint16Array</span>(<span
            class="pl-c1">8</span>);
<span class="pl-k">const</span> <span class="pl-c1">b</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint16Array</span>(<span class="pl-c1">10</span>);

<span class="pl-smi">b</span>.<span class="pl-c1">set</span>(a, <span class="pl-c1">2</span>)</pre>
    </div>
    <p>上面代码的<code>b</code>数组比<code>a</code>数组多两个成员，所以从<code>b[2]</code>开始复制。</p>
    <h3><a href="#typedarrayprototypesubarray"  class="anchor"
           id="user-content-typedarrayprototypesubarray">

    </a>TypedArray.prototype.subarray()
    </h3>
    <p><code>subarray</code>方法是对于 TypedArray 数组的一部分，再建立一个新的视图。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">a</span> <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Uint16Array</span>(<span
            class="pl-c1">8</span>);
<span class="pl-k">const</span> <span class="pl-c1">b</span> <span class="pl-k">=</span> <span
                class="pl-smi">a</span>.<span class="pl-en">subarray</span>(<span class="pl-c1">2</span>,<span
                class="pl-c1">3</span>);

<span class="pl-smi">a</span>.<span class="pl-smi">byteLength</span> <span class="pl-c"><span class="pl-c">//</span> 16</span>
<span class="pl-smi">b</span>.<span class="pl-smi">byteLength</span> <span class="pl-c"><span
                class="pl-c">//</span> 2</span></pre>
    </div>
    <p><code>subarray</code>方法的第一个参数是起始的成员序号，第二个参数是结束的成员序号（不含该成员），如果省略则包含剩余的全部成员。所以，上面代码的<code>a.subarray(2,3)</code>，意味着
        b 只包含<code>a[2]</code>一个成员，字节长度为 2。</p>
    <h3><a href="#typedarrayprototypeslice"  class="anchor"
           id="user-content-typedarrayprototypeslice">

    </a>TypedArray.prototype.slice()
    </h3>
    <p>TypeArray 实例的<code>slice</code>方法，可以返回一个指定位置的新的 TypedArray 实例。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> ui8 <span class="pl-k">=</span> <span
            class="pl-c1">Uint8Array</span>.<span class="pl-en">of</span>(<span class="pl-c1">0</span>, <span
            class="pl-c1">1</span>, <span class="pl-c1">2</span>);
<span class="pl-smi">ui8</span>.<span class="pl-c1">slice</span>(<span class="pl-k">-</span><span class="pl-c1">1</span>)
<span class="pl-c"><span class="pl-c">//</span> Uint8Array [ 2 ]</span></pre>
    </div>
    <p>上面代码中，<code>ui8</code>是 8 位无符号整数数组视图的一个实例。它的<code>slice</code>方法可以从当前视图之中，返回一个新的视图实例。</p>
    <p><code>slice</code>方法的参数，表示原数组的具体位置，开始生成新数组。负值表示逆向的位置，即-1 为倒数第一个位置，-2 表示倒数第二个位置，以此类推。</p>
    <h3><a href="#typedarrayof"  class="anchor" id="user-content-typedarrayof">

    </a>TypedArray.of()
    </h3>
    <p>TypedArray 数组的所有构造函数，都有一个静态方法<code>of</code>，用于将参数转为一个 TypedArray 实例。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c1">Float32Array</span>.<span
            class="pl-en">of</span>(<span class="pl-c1">0.151</span>, <span class="pl-k">-</span><span
            class="pl-c1">8</span>, <span class="pl-c1">3.7</span>)
<span class="pl-c"><span class="pl-c">//</span> Float32Array [ 0.151, -8, 3.7 ]</span></pre>
    </div>
    <p>下面三种方法都会生成同样一个 TypedArray 数组。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 方法一</span>
<span class="pl-k">let</span> tarr <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Uint8Array</span>([<span
                class="pl-c1">1</span>,<span class="pl-c1">2</span>,<span class="pl-c1">3</span>]);

<span class="pl-c"><span class="pl-c">//</span> 方法二</span>
<span class="pl-k">let</span> tarr <span class="pl-k">=</span> <span class="pl-c1">Uint8Array</span>.<span
                class="pl-en">of</span>(<span class="pl-c1">1</span>,<span class="pl-c1">2</span>,<span
                class="pl-c1">3</span>);

<span class="pl-c"><span class="pl-c">//</span> 方法三</span>
<span class="pl-k">let</span> tarr <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">Uint8Array</span>(<span
                class="pl-c1">3</span>);
tarr[<span class="pl-c1">0</span>] <span class="pl-k">=</span> <span class="pl-c1">1</span>;
tarr[<span class="pl-c1">1</span>] <span class="pl-k">=</span> <span class="pl-c1">2</span>;
tarr[<span class="pl-c1">2</span>] <span class="pl-k">=</span> <span class="pl-c1">3</span>;</pre>
    </div>
    <h3><a href="#typedarrayfrom"  class="anchor" id="user-content-typedarrayfrom">

    </a>TypedArray.from()
    </h3>
    <p>静态方法<code>from</code>接受一个可遍历的数据结构（比如数组）作为参数，返回一个基于这个结构的 TypedArray 实例。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c1">Uint16Array</span>.<span
            class="pl-en">from</span>([<span class="pl-c1">0</span>, <span class="pl-c1">1</span>, <span
            class="pl-c1">2</span>])
<span class="pl-c"><span class="pl-c">//</span> Uint16Array [ 0, 1, 2 ]</span></pre>
    </div>
    <p>这个方法还可以将一种 TypedArray 实例，转为另一种。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">ui16</span> <span class="pl-k">=</span> <span class="pl-c1">Uint16Array</span>.<span
            class="pl-en">from</span>(<span class="pl-c1">Uint8Array</span>.<span class="pl-en">of</span>(<span
            class="pl-c1">0</span>, <span class="pl-c1">1</span>, <span class="pl-c1">2</span>));
ui16 <span class="pl-k">instanceof</span> <span class="pl-c1">Uint16Array</span> <span class="pl-c"><span class="pl-c">//</span> true</span></pre>
    </div>
    <p><code>from</code>方法还可以接受一个函数，作为第二个参数，用来对每个元素进行遍历，功能类似<code>map</code>方法。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c1">Int8Array</span>.<span
            class="pl-en">of</span>(<span class="pl-c1">127</span>, <span class="pl-c1">126</span>, <span class="pl-c1">125</span>).<span
            class="pl-en">map</span>(<span class="pl-smi">x</span> <span class="pl-k">=&gt;</span> <span
            class="pl-c1">2</span> <span class="pl-k">*</span> x)
<span class="pl-c"><span class="pl-c">//</span> Int8Array [ -2, -4, -6 ]</span>

<span class="pl-c1">Int16Array</span>.<span class="pl-en">from</span>(<span class="pl-c1">Int8Array</span>.<span
                class="pl-en">of</span>(<span class="pl-c1">127</span>, <span class="pl-c1">126</span>, <span
                class="pl-c1">125</span>), <span class="pl-smi">x</span> <span class="pl-k">=&gt;</span> <span
                class="pl-c1">2</span> <span class="pl-k">*</span> x)
<span class="pl-c"><span class="pl-c">//</span> Int16Array [ 254, 252, 250 ]</span></pre>
    </div>
    <p>上面的例子中，<code>from</code>方法没有发生溢出，这说明遍历不是针对原来的 8 位整数数组。也就是说，<code>from</code>会将第一个参数指定的 TypedArray
        数组，拷贝到另一段内存之中，处理之后再将结果转成指定的数组格式。</p>
    <h2><a href="#复合视图"  class="anchor" id="user-content-复合视图">

    </a>复合视图
    </h2>
    <p>由于视图的构造函数可以指定起始位置和长度，所以在同一段内存之中，可以依次存放不同类型的数据，这叫做“复合视图”。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">24</span>);

<span class="pl-k">const</span> <span class="pl-c1">idView</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint32Array</span>(buffer, <span
                class="pl-c1">0</span>, <span class="pl-c1">1</span>);
<span class="pl-k">const</span> <span class="pl-c1">usernameView</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Uint8Array</span>(buffer, <span class="pl-c1">4</span>, <span class="pl-c1">16</span>);
<span class="pl-k">const</span> <span class="pl-c1">amountDueView</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Float32Array</span>(buffer, <span class="pl-c1">20</span>, <span class="pl-c1">1</span>);</pre>
    </div>
    <p>上面代码将一个 24 字节长度的<code>ArrayBuffer</code>对象，分成三个部分：</p>
    <ul>
        <li>字节 0 到字节 3：1 个 32 位无符号整数</li>
        <li>字节 4 到字节 19：16 个 8 位整数</li>
        <li>字节 20 到字节 23：1 个 32 位浮点数</li>
    </ul>
    <p>这种数据结构可以用如下的 C 语言描述：</p>
    <div class="highlight highlight-source-c"><pre><span class="pl-k">struct</span> someStruct {
  <span class="pl-k">unsigned</span> <span class="pl-k">long</span> id;
  <span class="pl-k">char</span> username[<span class="pl-c1">16</span>];
  <span class="pl-k">float</span> amountDue;
};</pre>
    </div>
    <h2><a href="#dataview-视图"  class="anchor" id="user-content-dataview-视图">

    </a>DataView 视图
    </h2>
    <p>如果一段数据包括多种类型（比如服务器传来的 HTTP 数据），这时除了建立<code>ArrayBuffer</code>对象的复合视图以外，还可以通过<code>DataView</code>视图进行操作。</p>
    <p><code>DataView</code>视图提供更多操作选项，而且支持设定字节序。本来，在设计目的上，<code>ArrayBuffer</code>对象的各种 TypedArray
        视图，是用来向网卡、声卡之类的本机设备传送数据，所以使用本机的字节序就可以了；而<code>DataView</code>视图的设计目的，是用来处理网络设备传来的数据，所以大端字节序或小端字节序是可以自行设定的。</p>
    <p><code>DataView</code>视图本身也是构造函数，接受一个<code>ArrayBuffer</code>对象作为参数，生成视图。</p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-c1">DataView</span>(<span class="pl-c1">ArrayBuffer</span> buffer [, 字节起始位置 [, 长度]]);</pre>
    </div>
    <p>下面是一个例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">24</span>);
<span class="pl-k">const</span> <span class="pl-c1">dv</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">DataView</span>(buffer);</pre>
    </div>
    <p><code>DataView</code>实例有以下属性，含义与 TypedArray 实例的同名方法相同。</p>
    <ul>
        <li><code>DataView.prototype.buffer</code>：返回对应的 ArrayBuffer 对象</li>
        <li><code>DataView.prototype.byteLength</code>：返回占据的内存字节长度</li>
        <li><code>DataView.prototype.byteOffset</code>：返回当前视图从对应的 ArrayBuffer 对象的哪个字节开始</li>
    </ul>
    <p><code>DataView</code>实例提供 8 个方法读取内存。</p>
    <ul>
        <li><strong><code>getInt8</code></strong>：读取 1 个字节，返回一个 8 位整数。</li>
        <li><strong><code>getUint8</code></strong>：读取 1 个字节，返回一个无符号的 8 位整数。</li>
        <li><strong><code>getInt16</code></strong>：读取 2 个字节，返回一个 16 位整数。</li>
        <li><strong><code>getUint16</code></strong>：读取 2 个字节，返回一个无符号的 16 位整数。</li>
        <li><strong><code>getInt32</code></strong>：读取 4 个字节，返回一个 32 位整数。</li>
        <li><strong><code>getUint32</code></strong>：读取 4 个字节，返回一个无符号的 32 位整数。</li>
        <li><strong><code>getFloat32</code></strong>：读取 4 个字节，返回一个 32 位浮点数。</li>
        <li><strong><code>getFloat64</code></strong>：读取 8 个字节，返回一个 64 位浮点数。</li>
    </ul>
    <p>这一系列<code>get</code>方法的参数都是一个字节序号（不能是负数，否则会报错），表示从哪个字节开始读取。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">buffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span
            class="pl-c1">24</span>);
<span class="pl-k">const</span> <span class="pl-c1">dv</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">DataView</span>(buffer);

<span class="pl-c"><span class="pl-c">//</span> 从第1个字节读取一个8位无符号整数</span>
<span class="pl-k">const</span> <span class="pl-c1">v1</span> <span class="pl-k">=</span> <span class="pl-smi">dv</span>.<span
                class="pl-en">getUint8</span>(<span class="pl-c1">0</span>);

<span class="pl-c"><span class="pl-c">//</span> 从第2个字节读取一个16位无符号整数</span>
<span class="pl-k">const</span> <span class="pl-c1">v2</span> <span class="pl-k">=</span> <span class="pl-smi">dv</span>.<span
                class="pl-en">getUint16</span>(<span class="pl-c1">1</span>);

<span class="pl-c"><span class="pl-c">//</span> 从第4个字节读取一个16位无符号整数</span>
<span class="pl-k">const</span> <span class="pl-c1">v3</span> <span class="pl-k">=</span> <span class="pl-smi">dv</span>.<span
                class="pl-en">getUint16</span>(<span class="pl-c1">3</span>);</pre>
    </div>
    <p>上面代码读取了<code>ArrayBuffer</code>对象的前 5 个字节，其中有一个 8 位整数和两个十六位整数。</p>
    <p>如果一次读取两个或两个以上字节，就必须明确数据的存储方式，到底是小端字节序还是大端字节序。默认情况下，<code>DataView</code>的<code>get</code>方法使用大端字节序解读数据，如果需要使用小端字节序解读，必须在<code>get</code>方法的第二个参数指定<code>true</code>。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 小端字节序</span>
<span class="pl-k">const</span> <span class="pl-c1">v1</span> <span class="pl-k">=</span> <span class="pl-smi">dv</span>.<span
                class="pl-en">getUint16</span>(<span class="pl-c1">1</span>, <span class="pl-c1">true</span>);

<span class="pl-c"><span class="pl-c">//</span> 大端字节序</span>
<span class="pl-k">const</span> <span class="pl-c1">v2</span> <span class="pl-k">=</span> <span class="pl-smi">dv</span>.<span
                class="pl-en">getUint16</span>(<span class="pl-c1">3</span>, <span class="pl-c1">false</span>);

<span class="pl-c"><span class="pl-c">//</span> 大端字节序</span>
<span class="pl-k">const</span> <span class="pl-c1">v3</span> <span class="pl-k">=</span> <span class="pl-smi">dv</span>.<span
                class="pl-en">getUint16</span>(<span class="pl-c1">3</span>);</pre>
    </div>
    <p>DataView 视图提供 8 个方法写入内存。</p>
    <ul>
        <li><strong><code>setInt8</code></strong>：写入 1 个字节的 8 位整数。</li>
        <li><strong><code>setUint8</code></strong>：写入 1 个字节的 8 位无符号整数。</li>
        <li><strong><code>setInt16</code></strong>：写入 2 个字节的 16 位整数。</li>
        <li><strong><code>setUint16</code></strong>：写入 2 个字节的 16 位无符号整数。</li>
        <li><strong><code>setInt32</code></strong>：写入 4 个字节的 32 位整数。</li>
        <li><strong><code>setUint32</code></strong>：写入 4 个字节的 32 位无符号整数。</li>
        <li><strong><code>setFloat32</code></strong>：写入 4 个字节的 32 位浮点数。</li>
        <li><strong><code>setFloat64</code></strong>：写入 8 个字节的 64 位浮点数。</li>
    </ul>
    <p>这一系列<code>set</code>方法，接受两个参数，第一个参数是字节序号，表示从哪个字节开始写入，第二个参数为写入的数据。对于那些写入两个或两个以上字节的方法，需要指定第三个参数，<code>false</code>或者<code>undefined</code>表示使用大端字节序写入，<code>true</code>表示使用小端字节序写入。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 在第1个字节，以大端字节序写入值为25的32位整数</span>
<span class="pl-smi">dv</span>.<span class="pl-en">setInt32</span>(<span class="pl-c1">0</span>, <span
                class="pl-c1">25</span>, <span class="pl-c1">false</span>);

<span class="pl-c"><span class="pl-c">//</span> 在第5个字节，以大端字节序写入值为25的32位整数</span>
<span class="pl-smi">dv</span>.<span class="pl-en">setInt32</span>(<span class="pl-c1">4</span>, <span
                class="pl-c1">25</span>);

<span class="pl-c"><span class="pl-c">//</span> 在第9个字节，以小端字节序写入值为2.5的32位浮点数</span>
<span class="pl-smi">dv</span>.<span class="pl-en">setFloat32</span>(<span class="pl-c1">8</span>, <span class="pl-c1">2.5</span>, <span
                class="pl-c1">true</span>);</pre>
    </div>
    <p>如果不确定正在使用的计算机的字节序，可以采用下面的判断方式。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">littleEndian</span> <span class="pl-k">=</span> (<span class="pl-k">function</span>() {
  <span class="pl-k">const</span> <span class="pl-c1">buffer</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">ArrayBuffer</span>(<span class="pl-c1">2</span>);
  <span class="pl-k">new</span> <span class="pl-en">DataView</span>(buffer).<span class="pl-en">setInt16</span>(<span
                class="pl-c1">0</span>, <span class="pl-c1">256</span>, <span class="pl-c1">true</span>);
  <span class="pl-k">return</span> <span class="pl-k">new</span> <span class="pl-en">Int16Array</span>(buffer)[<span
                class="pl-c1">0</span>] <span class="pl-k">===</span> <span class="pl-c1">256</span>;
})();</pre>
    </div>
    <p>如果返回<code>true</code>，就是小端字节序；如果返回<code>false</code>，就是大端字节序。</p>
    <h2><a href="#二进制数组的应用"  class="anchor" id="user-content-二进制数组的应用">

    </a>二进制数组的应用
    </h2>
    <p>大量的 Web API 用到了<code>ArrayBuffer</code>对象和它的视图对象。</p>
    <h3><a href="#ajax"  class="anchor" id="user-content-ajax">

    </a>AJAX
    </h3>
    <p>传统上，服务器通过 AJAX 操作只能返回文本数据，即<code>responseType</code>属性默认为<code>text</code>。<code>XMLHttpRequest</code>第二版<code>XHR2</code>允许服务器返回二进制数据，这时分成两种情况。如果明确知道返回的二进制数据类型，可以把返回类型（<code>responseType</code>）设为<code>arraybuffer</code>；如果不知道，就设为<code>blob</code>。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> xhr <span class="pl-k">=</span> <span
            class="pl-k">new</span> <span class="pl-en">XMLHttpRequest</span>();
<span class="pl-smi">xhr</span>.<span class="pl-c1">open</span>(<span class="pl-s"><span class="pl-pds">'</span>GET<span
                class="pl-pds">'</span></span>, someUrl);
<span class="pl-smi">xhr</span>.<span class="pl-smi">responseType</span> <span class="pl-k">=</span> <span class="pl-s"><span
                class="pl-pds">'</span>arraybuffer<span class="pl-pds">'</span></span>;

<span class="pl-smi">xhr</span>.<span class="pl-en">onload</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {
  <span class="pl-k">let</span> arrayBuffer <span class="pl-k">=</span> <span class="pl-smi">xhr</span>.<span
                class="pl-smi">response</span>;
  <span class="pl-c"><span class="pl-c">//</span> ···</span>
};

<span class="pl-smi">xhr</span>.<span class="pl-c1">send</span>();</pre>
    </div>
    <p>如果知道传回来的是 32 位整数，可以像下面这样处理。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-smi">xhr</span>.<span class="pl-en">onreadystatechange</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span> () {
  <span class="pl-k">if</span> (<span class="pl-smi">req</span>.<span class="pl-c1">readyState</span> <span
                class="pl-k">===</span> <span class="pl-c1">4</span> ) {
    <span class="pl-k">const</span> <span class="pl-c1">arrayResponse</span> <span class="pl-k">=</span> <span
                class="pl-smi">xhr</span>.<span class="pl-smi">response</span>;
    <span class="pl-k">const</span> <span class="pl-c1">dataView</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">DataView</span>(arrayResponse);
    <span class="pl-k">const</span> <span class="pl-c1">ints</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint32Array</span>(<span
                class="pl-smi">dataView</span>.<span class="pl-smi">byteLength</span> <span class="pl-k">/</span> <span
                class="pl-c1">4</span>);

    <span class="pl-smi">xhrDiv</span>.<span class="pl-c1">style</span>.<span class="pl-c1">backgroundColor</span> <span
                class="pl-k">=</span> <span class="pl-s"><span class="pl-pds">"</span>#00FF00<span
                class="pl-pds">"</span></span>;
    <span class="pl-smi">xhrDiv</span>.<span class="pl-smi">innerText</span> <span class="pl-k">=</span> <span
                class="pl-s"><span class="pl-pds">"</span>Array is <span class="pl-pds">"</span></span> <span
                class="pl-k">+</span> <span class="pl-smi">ints</span>.<span class="pl-c1">length</span> <span
                class="pl-k">+</span> <span class="pl-s"><span class="pl-pds">"</span>uints long<span
                class="pl-pds">"</span></span>;
  }
}</pre>
    </div>
    <h3><a href="#canvas"  class="anchor" id="user-content-canvas">

    </a>Canvas
    </h3>
    <p>网页<code>Canvas</code>元素输出的二进制像素数据，就是 TypedArray 数组。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">canvas</span> <span class="pl-k">=</span> <span class="pl-c1">document</span>.<span
            class="pl-c1">getElementById</span>(<span class="pl-s"><span class="pl-pds">'</span>myCanvas<span
            class="pl-pds">'</span></span>);
<span class="pl-k">const</span> <span class="pl-c1">ctx</span> <span class="pl-k">=</span> <span
                class="pl-smi">canvas</span>.<span class="pl-c1">getContext</span>(<span class="pl-s"><span
                class="pl-pds">'</span>2d<span class="pl-pds">'</span></span>);

<span class="pl-k">const</span> <span class="pl-c1">imageData</span> <span class="pl-k">=</span> <span class="pl-smi">ctx</span>.<span
                class="pl-en">getImageData</span>(<span class="pl-c1">0</span>, <span class="pl-c1">0</span>, <span
                class="pl-smi">canvas</span>.<span class="pl-c1">width</span>, <span class="pl-smi">canvas</span>.<span
                class="pl-c1">height</span>);
<span class="pl-k">const</span> <span class="pl-c1">uint8ClampedArray</span> <span class="pl-k">=</span> <span
                class="pl-smi">imageData</span>.<span class="pl-c1">data</span>;</pre>
    </div>
    <p>需要注意的是，上面代码的<code>uint8ClampedArray</code>虽然是一个 TypedArray 数组，但是它的视图类型是一种针对<code>Canvas</code>元素的专有类型<code>Uint8ClampedArray</code>。这个视图类型的特点，就是专门针对颜色，把每个字节解读为无符号的
        8 位整数，即只能取值 0 ～ 255，而且发生运算的时候自动过滤高位溢出。这为图像处理带来了巨大的方便。</p>
    <p>举例来说，如果把像素的颜色值设为<code>Uint8Array</code>类型，那么乘以一个 gamma 值的时候，就必须这样计算：</p>
    <div class="highlight highlight-source-js">
        <pre>u8[i] <span class="pl-k">=</span> <span class="pl-c1">Math</span>.<span class="pl-c1">min</span>(<span
                class="pl-c1">255</span>, <span class="pl-c1">Math</span>.<span class="pl-c1">max</span>(<span
                class="pl-c1">0</span>, u8[i] <span class="pl-k">*</span> gamma));</pre>
    </div>
    <p>因为<code>Uint8Array</code>类型对于大于 255 的运算结果（比如<code>0xFF+1</code>），会自动变为<code>0x00</code>，所以图像处理必须要像上面这样算。这样做很麻烦，而且影响性能。如果将颜色值设为<code>Uint8ClampedArray</code>类型，计算就简化许多。
    </p>
    <div class="highlight highlight-source-js">
        <pre>pixels[i] <span class="pl-k">*=</span> gamma;</pre>
    </div>
    <p><code>Uint8ClampedArray</code>类型确保将小于 0 的值设为 0，将大于 255 的值设为 255。注意，IE 10 不支持该类型。</p>
    <h3><a href="#websocket"  class="anchor" id="user-content-websocket">

    </a>WebSocket
    </h3>
    <p><code>WebSocket</code>可以通过<code>ArrayBuffer</code>，发送或接收二进制数据。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> socket <span
            class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">WebSocket</span>(<span class="pl-s"><span
            class="pl-pds">'</span>ws://127.0.0.1:8081<span class="pl-pds">'</span></span>);
<span class="pl-smi">socket</span>.<span class="pl-smi">binaryType</span> <span class="pl-k">=</span> <span
                class="pl-s"><span class="pl-pds">'</span>arraybuffer<span class="pl-pds">'</span></span>;

<span class="pl-c"><span class="pl-c">//</span> Wait until socket is open</span>
<span class="pl-smi">socket</span>.<span class="pl-c1">addEventListener</span>(<span class="pl-s"><span
                class="pl-pds">'</span>open<span class="pl-pds">'</span></span>, <span
                class="pl-k">function</span> (<span class="pl-c1">event</span>) {
  <span class="pl-c"><span class="pl-c">//</span> Send binary data</span>
  <span class="pl-k">const</span> <span class="pl-c1">typedArray</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Uint8Array</span>(<span class="pl-c1">4</span>);
  <span class="pl-smi">socket</span>.<span class="pl-c1">send</span>(<span class="pl-smi">typedArray</span>.<span
                class="pl-smi">buffer</span>);
});

<span class="pl-c"><span class="pl-c">//</span> Receive binary data</span>
<span class="pl-smi">socket</span>.<span class="pl-c1">addEventListener</span>(<span class="pl-s"><span
                class="pl-pds">'</span>message<span class="pl-pds">'</span></span>, <span class="pl-k">function</span> (<span
                class="pl-c1">event</span>) {
  <span class="pl-k">const</span> <span class="pl-c1">arrayBuffer</span> <span class="pl-k">=</span> <span
                class="pl-c1">event</span>.<span class="pl-c1">data</span>;
  <span class="pl-c"><span class="pl-c">//</span> ···</span>
});</pre>
    </div>
    <h3><a href="#fetch-api"  class="anchor" id="user-content-fetch-api">

    </a>Fetch API
    </h3>
    <p>Fetch API 取回的数据，就是<code>ArrayBuffer</code>对象。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-en">fetch</span>(url)
.<span class="pl-en">then</span>(<span class="pl-k">function</span>(<span class="pl-smi">response</span>){
  <span class="pl-k">return</span> <span class="pl-smi">response</span>.<span class="pl-en">arrayBuffer</span>()
})
.<span class="pl-en">then</span>(<span class="pl-k">function</span>(<span class="pl-smi">arrayBuffer</span>){
  <span class="pl-c"><span class="pl-c">//</span> ...</span>
});</pre>
    </div>
    <h3><a href="#file-api"  class="anchor" id="user-content-file-api">

    </a>File API
    </h3>
    <p>如果知道一个文件的二进制数据类型，也可以将这个文件读取为<code>ArrayBuffer</code>对象。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">fileInput</span> <span
            class="pl-k">=</span> <span class="pl-c1">document</span>.<span class="pl-c1">getElementById</span>(<span
            class="pl-s"><span class="pl-pds">'</span>fileInput<span class="pl-pds">'</span></span>);
<span class="pl-k">const</span> <span class="pl-c1">file</span> <span class="pl-k">=</span> <span class="pl-smi">fileInput</span>.<span
                class="pl-smi">files</span>[<span class="pl-c1">0</span>];
<span class="pl-k">const</span> <span class="pl-c1">reader</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">FileReader</span>();
<span class="pl-smi">reader</span>.<span class="pl-en">readAsArrayBuffer</span>(file);
<span class="pl-smi">reader</span>.<span class="pl-en">onload</span> <span class="pl-k">=</span> <span class="pl-k">function</span> () {
  <span class="pl-k">const</span> <span class="pl-c1">arrayBuffer</span> <span class="pl-k">=</span> <span
                class="pl-smi">reader</span>.<span class="pl-smi">result</span>;
  <span class="pl-c"><span class="pl-c">//</span> ···</span>
};</pre>
    </div>
    <p>下面以处理 bmp 文件为例。假定<code>file</code>变量是一个指向 bmp 文件的文件对象，首先读取文件。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">reader</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">FileReader</span>();
<span class="pl-smi">reader</span>.<span class="pl-c1">addEventListener</span>(<span class="pl-s"><span
                class="pl-pds">"</span>load<span class="pl-pds">"</span></span>, processimage, <span
                class="pl-c1">false</span>);
<span class="pl-smi">reader</span>.<span class="pl-en">readAsArrayBuffer</span>(file);</pre>
    </div>
    <p>
        然后，定义处理图像的回调函数：先在二进制数据之上建立一个<code>DataView</code>视图，再建立一个<code>bitmap</code>对象，用于存放处理后的数据，最后将图像展示在<code>Canvas</code>元素之中。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span> <span
            class="pl-en">processimage</span>(<span class="pl-smi">e</span>) {
  <span class="pl-k">const</span> <span class="pl-c1">buffer</span> <span class="pl-k">=</span> <span
                class="pl-smi">e</span>.<span class="pl-c1">target</span>.<span class="pl-smi">result</span>;
  <span class="pl-k">const</span> <span class="pl-c1">datav</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">DataView</span>(buffer);
  <span class="pl-k">const</span> <span class="pl-c1">bitmap</span> <span class="pl-k">=</span> {};
  <span class="pl-c"><span class="pl-c">//</span> 具体的处理步骤</span>
}</pre>
    </div>
    <p>具体处理图像数据时，先处理 bmp 的文件头。具体每个文件头的格式和定义，请参阅有关资料。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-smi">bitmap</span>.<span
            class="pl-smi">fileheader</span> <span class="pl-k">=</span> {};
<span class="pl-smi">bitmap</span>.<span class="pl-smi">fileheader</span>.<span class="pl-smi">bfType</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint16</span>(<span
                class="pl-c1">0</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">fileheader</span>.<span class="pl-smi">bfSize</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span
                class="pl-c1">2</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">fileheader</span>.<span class="pl-smi">bfReserved1</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint16</span>(<span
                class="pl-c1">6</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">fileheader</span>.<span class="pl-smi">bfReserved2</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint16</span>(<span
                class="pl-c1">8</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">fileheader</span>.<span class="pl-smi">bfOffBits</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span
                class="pl-c1">10</span>, <span class="pl-c1">true</span>);</pre>
    </div>
    <p>接着处理图像元信息部分。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-smi">bitmap</span>.<span
            class="pl-smi">infoheader</span> <span class="pl-k">=</span> {};
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span class="pl-smi">biSize</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span
                class="pl-c1">14</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span class="pl-smi">biWidth</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span
                class="pl-c1">18</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span class="pl-smi">biHeight</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span
                class="pl-c1">22</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span class="pl-smi">biPlanes</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint16</span>(<span
                class="pl-c1">26</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span class="pl-smi">biBitCount</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint16</span>(<span
                class="pl-c1">28</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span
                class="pl-smi">biCompression</span> <span class="pl-k">=</span> <span class="pl-smi">datav</span>.<span
                class="pl-en">getUint32</span>(<span class="pl-c1">30</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span class="pl-smi">biSizeImage</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span
                class="pl-c1">34</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span
                class="pl-smi">biXPelsPerMeter</span> <span class="pl-k">=</span> <span
                class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span class="pl-c1">38</span>, <span
                class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span
                class="pl-smi">biYPelsPerMeter</span> <span class="pl-k">=</span> <span
                class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span class="pl-c1">42</span>, <span
                class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span class="pl-smi">biClrUsed</span> <span
                class="pl-k">=</span> <span class="pl-smi">datav</span>.<span class="pl-en">getUint32</span>(<span
                class="pl-c1">46</span>, <span class="pl-c1">true</span>);
<span class="pl-smi">bitmap</span>.<span class="pl-smi">infoheader</span>.<span
                class="pl-smi">biClrImportant</span> <span class="pl-k">=</span> <span class="pl-smi">datav</span>.<span
                class="pl-en">getUint32</span>(<span class="pl-c1">50</span>, <span class="pl-c1">true</span>);</pre>
    </div>
    <p>最后处理图像本身的像素信息。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span
            class="pl-c1">start</span> <span class="pl-k">=</span> <span class="pl-smi">bitmap</span>.<span
            class="pl-smi">fileheader</span>.<span class="pl-smi">bfOffBits</span>;
<span class="pl-smi">bitmap</span>.<span class="pl-smi">pixels</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Uint8Array</span>(buffer, start);</pre>
    </div>
    <p>至此，图像文件的数据全部处理完成。下一步，可以根据需要，进行图像变形，或者转换格式，或者展示在<code>Canvas</code>网页元素之中。</p>
    <h2><a href="#sharedarraybuffer"  class="anchor" id="user-content-sharedarraybuffer">

    </a>SharedArrayBuffer
    </h2>
    <p>JavaScript 是单线程的，Web worker 引入了多线程：主线程用来与用户互动，Worker 线程用来承担计算任务。每个线程的数据都是隔离的，通过<code>postMessage()</code>通信。下面是一个例子。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 主线程</span>
<span class="pl-k">const</span> <span class="pl-c1">w</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">Worker</span>(<span class="pl-s"><span
                class="pl-pds">'</span>myworker.js<span class="pl-pds">'</span></span>);</pre>
    </div>
    <p>上面代码中，主线程新建了一个 Worker 线程。该线程与主线程之间会有一个通信渠道，主线程通过<code>w.postMessage</code>向 Worker 线程发消息，同时通过<code>message</code>事件监听
        Worker 线程的回应。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 主线程</span>
<span class="pl-smi">w</span>.<span class="pl-c1">postMessage</span>(<span class="pl-s"><span
                class="pl-pds">'</span>hi<span class="pl-pds">'</span></span>);
<span class="pl-smi">w</span>.<span class="pl-en">onmessage</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span
                class="pl-smi">ev</span>) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-smi">ev</span>.<span class="pl-c1">data</span>);
}</pre>
    </div>
    <p>上面代码中，主线程先发一个消息<code>hi</code>，然后在监听到 Worker 线程的回应后，就将其打印出来。</p>
    <p>Worker 线程也是通过监听<code>message</code>事件，来获取主线程发来的消息，并作出反应。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> Worker 线程</span>
<span class="pl-en">onmessage</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span
                class="pl-smi">ev</span>) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-smi">ev</span>.<span class="pl-c1">data</span>);
  <span class="pl-en">postMessage</span>(<span class="pl-s"><span class="pl-pds">'</span>ho<span class="pl-pds">'</span></span>);
}</pre>
    </div>
    <p>线程之间的数据交换可以是各种格式，不仅仅是字符串，也可以是二进制数据。这种交换采用的是复制机制，即一个进程将需要分享的数据复制一份，通过<code>postMessage</code>方法交给另一个进程。如果数据量比较大，这种通信的效率显然比较低。很容易想到，这时可以留出一块内存区域，由主线程与
        Worker 线程共享，两方都可以读写，那么就会大大提高效率，协作起来也会比较简单（不像<code>postMessage</code>那么麻烦）。</p>
    <p>ES2017 引入<a
            href="https://github.com/tc39/ecmascript_sharedmem/blob/master/TUTORIAL.md"><code>SharedArrayBuffer</code></a>，允许
        Worker 线程与主线程共享同一块内存。<code>SharedArrayBuffer</code>的 API 与<code>ArrayBuffer</code>一模一样，唯一的区别是后者无法共享。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 主线程</span>

<span class="pl-c"><span class="pl-c">//</span> 新建 1KB 共享内存</span>
<span class="pl-k">const</span> <span class="pl-c1">sharedBuffer</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">SharedArrayBuffer</span>(<span class="pl-c1">1024</span>);

<span class="pl-c"><span class="pl-c">//</span> 主线程将共享内存的地址发送出去</span>
<span class="pl-smi">w</span>.<span class="pl-c1">postMessage</span>(sharedBuffer);

<span class="pl-c"><span class="pl-c">//</span> 在共享内存上建立视图，供写入数据</span>
<span class="pl-k">const</span> <span class="pl-c1">sharedArray</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int32Array</span>(sharedBuffer);</pre>
    </div>
    <p>上面代码中，<code>postMessage</code>方法的参数是<code>SharedArrayBuffer</code>对象。</p>
    <p>Worker 线程从事件的<code>data</code>属性上面取到数据。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> Worker 线程</span>
<span class="pl-en">onmessage</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span
                class="pl-smi">ev</span>) {
  <span class="pl-c"><span class="pl-c">//</span> 主线程共享的数据，就是 1KB 的共享内存</span>
  <span class="pl-k">const</span> <span class="pl-c1">sharedBuffer</span> <span class="pl-k">=</span> <span
                class="pl-smi">ev</span>.<span class="pl-c1">data</span>;

  <span class="pl-c"><span class="pl-c">//</span> 在共享内存上建立视图，方便读写</span>
  <span class="pl-k">const</span> <span class="pl-c1">sharedArray</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int32Array</span>(sharedBuffer);

  <span class="pl-c"><span class="pl-c">//</span> ...</span>
};</pre>
    </div>
    <p>共享内存也可以在 Worker 线程创建，发给主线程。</p>
    <p><code>SharedArrayBuffer</code>与<code>ArrayBuffer</code>一样，本身是无法读写的，必须在上面建立视图，然后通过视图读写。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 分配 10 万个 32 位整数占据的内存空间</span>
<span class="pl-k">const</span> <span class="pl-c1">sab</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">SharedArrayBuffer</span>(<span class="pl-c1">Int32Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span
                class="pl-k">*</span> <span class="pl-c1">100000</span>);

<span class="pl-c"><span class="pl-c">//</span> 建立 32 位整数视图</span>
<span class="pl-k">const</span> <span class="pl-c1">ia</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int32Array</span>(sab);  <span class="pl-c"><span class="pl-c">//</span> ia.length == 100000</span>

<span class="pl-c"><span class="pl-c">//</span> 新建一个质数生成器</span>
<span class="pl-k">const</span> <span class="pl-c1">primes</span> <span class="pl-k">=</span> <span
                class="pl-k">new</span> <span class="pl-en">PrimeGenerator</span>();

<span class="pl-c"><span class="pl-c">//</span> 将 10 万个质数，写入这段内存空间</span>
<span class="pl-k">for</span> ( <span class="pl-k">let</span> i<span class="pl-k">=</span><span class="pl-c1">0</span> ; i <span
                class="pl-k">&lt;</span> <span class="pl-smi">ia</span>.<span class="pl-c1">length</span> ; i<span
                class="pl-k">++</span> )
  ia[i] <span class="pl-k">=</span> <span class="pl-smi">primes</span>.<span class="pl-c1">next</span>();

<span class="pl-c"><span class="pl-c">//</span> 向 Worker 线程发送这段共享内存</span>
<span class="pl-smi">w</span>.<span class="pl-c1">postMessage</span>(ia);</pre>
    </div>
    <p>Worker 线程收到数据后的处理如下。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> Worker 线程</span>
<span class="pl-k">let</span> ia;
<span class="pl-en">onmessage</span> <span class="pl-k">=</span> <span class="pl-k">function</span> (<span
                class="pl-smi">ev</span>) {
  ia <span class="pl-k">=</span> <span class="pl-smi">ev</span>.<span class="pl-c1">data</span>;
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-smi">ia</span>.<span class="pl-c1">length</span>); <span
                class="pl-c"><span class="pl-c">//</span> 100000</span>
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(ia[<span class="pl-c1">37</span>]); <span
                class="pl-c"><span class="pl-c">//</span> 输出 163，因为这是第38个质数</span>
};</pre>
    </div>
    <h2><a href="#atomics-对象"  class="anchor" id="user-content-atomics-对象">

    </a>Atomics 对象
    </h2>
    <p>多线程共享内存，最大的问题就是如何防止两个线程同时修改某个地址，或者说，当一个线程修改共享内存以后，必须有一个机制让其他线程同步。SharedArrayBuffer API 提供<code>Atomics</code>对象，保证所有共享内存的操作都是“原子性”的，并且可以在所有线程内同步。
    </p>
    <p>
        什么叫“原子性操作”呢？现代编程语言中，一条普通的命令被编译器处理以后，会变成多条机器指令。如果是单线程运行，这是没有问题的；多线程环境并且共享内存时，就会出问题，因为这一组机器指令的运行期间，可能会插入其他线程的指令，从而导致运行结果出错。请看下面的例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 主线程</span>
ia[<span class="pl-c1">42</span>] <span class="pl-k">=</span> <span class="pl-c1">314159</span>;  <span
                class="pl-c"><span class="pl-c">//</span> 原先的值 191</span>
ia[<span class="pl-c1">37</span>] <span class="pl-k">=</span> <span class="pl-c1">123456</span>;  <span
                class="pl-c"><span class="pl-c">//</span> 原先的值 163</span>

<span class="pl-c"><span class="pl-c">//</span> Worker 线程</span>
<span class="pl-en">console</span>.<span class="pl-c1">log</span>(ia[<span class="pl-c1">37</span>]);
<span class="pl-en">console</span>.<span class="pl-c1">log</span>(ia[<span class="pl-c1">42</span>]);
<span class="pl-c"><span class="pl-c">//</span> 可能的结果</span>
<span class="pl-c"><span class="pl-c">//</span> 123456</span>
<span class="pl-c"><span class="pl-c">//</span> 191</span></pre>
    </div>
    <p>上面代码中，主线程的原始顺序是先对 42 号位置赋值，再对 37 号位置赋值。但是，编译器和 CPU 为了优化，可能会改变这两个操作的执行顺序（因为它们之间互不依赖），先对 37 号位置赋值，再对 42
        号位置赋值。而执行到一半的时候，Worker 线程可能就会来读取数据，导致打印出<code>123456</code>和<code>191</code>。</p>
    <p>下面是另一个例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 主线程</span>
<span class="pl-k">const</span> <span class="pl-c1">sab</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">SharedArrayBuffer</span>(<span class="pl-c1">Int32Array</span>.<span class="pl-c1">BYTES_PER_ELEMENT</span> <span
                class="pl-k">*</span> <span class="pl-c1">100000</span>);
<span class="pl-k">const</span> <span class="pl-c1">ia</span> <span class="pl-k">=</span> <span class="pl-k">new</span> <span
                class="pl-en">Int32Array</span>(sab);

<span class="pl-k">for</span> (<span class="pl-k">let</span> i <span class="pl-k">=</span> <span class="pl-c1">0</span>; i <span
                class="pl-k">&lt;</span> <span class="pl-smi">ia</span>.<span class="pl-c1">length</span>; i<span
                class="pl-k">++</span>) {
  ia[i] <span class="pl-k">=</span> <span class="pl-smi">primes</span>.<span class="pl-c1">next</span>(); <span
                class="pl-c"><span class="pl-c">//</span> 将质数放入 ia</span>
}

<span class="pl-c"><span class="pl-c">//</span> worker 线程</span>
ia[<span class="pl-c1">112</span>]<span class="pl-k">++</span>; <span class="pl-c"><span
                class="pl-c">//</span> 错误</span>
<span class="pl-c1">Atomics</span>.<span class="pl-c1">add</span>(ia, <span class="pl-c1">112</span>, <span
                class="pl-c1">1</span>); <span class="pl-c"><span class="pl-c">//</span> 正确</span></pre>
    </div>
    <p>上面代码中，Worker 线程直接改写共享内存<code>ia[112]++</code>是不正确的。因为这行语句会被编译成多条机器指令，这些指令之间无法保证不会插入其他进程的指令。请设想如果两个线程同时<code>ia[112]++</code>，很可能它们得到的结果都是不正确的。
    </p>
    <p><code>Atomics</code>对象就是为了解决这个问题而提出，它可以保证一个操作所对应的多条机器指令，一定是作为一个整体运行的，中间不会被打断。也就是说，它所涉及的操作都可以看作是原子性的单操作，这可以避免线程竞争，提高多线程共享内存时的操作安全。所以，<code>ia[112]++</code>要改写成<code>Atomics.add(ia,
        112, 1)</code>。</p>
    <p><code>Atomics</code>对象提供多种方法。</p>
    <p><strong>（1）Atomics.store()，Atomics.load()</strong></p>
    <p><code>store()</code>方法用来向共享内存写入数据，<code>load()</code>方法用来从共享内存读出数据。比起直接的读写操作，它们的好处是保证了读写操作的原子性。</p>
    <p>
        此外，它们还用来解决一个问题：多个线程使用共享线程的某个位置作为开关（flag），一旦该位置的值变了，就执行特定操作。这时，必须保证该位置的赋值操作，一定是在它前面的所有可能会改写内存的操作结束后执行；而该位置的取值操作，一定是在它后面所有可能会读取该位置的操作开始之前执行。<code>store</code>方法和<code>load</code>方法就能做到这一点，编译器不会为了优化，而打乱机器指令的执行顺序。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c1">Atomics</span>.<span class="pl-c1">load</span>(array, index)
<span class="pl-c1">Atomics</span>.<span class="pl-en">store</span>(array, index, value)</pre>
    </div>
    <p><code>store</code>方法接受三个参数：SharedBuffer 的视图、位置索引和值，返回<code>sharedArray[index]</code>的值。<code>load</code>方法只接受两个参数：SharedBuffer
        的视图和位置索引，也是返回<code>sharedArray[index]</code>的值。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 主线程 main.js</span>
ia[<span class="pl-c1">42</span>] <span class="pl-k">=</span> <span class="pl-c1">314159</span>;  <span
                class="pl-c"><span class="pl-c">//</span> 原先的值 191</span>
<span class="pl-c1">Atomics</span>.<span class="pl-en">store</span>(ia, <span class="pl-c1">37</span>, <span
                class="pl-c1">123456</span>);  <span class="pl-c"><span class="pl-c">//</span> 原先的值是 163</span>

<span class="pl-c"><span class="pl-c">//</span> Worker 线程 worker.js</span>
<span class="pl-k">while</span> (<span class="pl-c1">Atomics</span>.<span class="pl-c1">load</span>(ia, <span
                class="pl-c1">37</span>) <span class="pl-k">==</span> <span class="pl-c1">163</span>);
<span class="pl-en">console</span>.<span class="pl-c1">log</span>(ia[<span class="pl-c1">37</span>]);  <span
                class="pl-c"><span class="pl-c">//</span> 123456</span>
<span class="pl-en">console</span>.<span class="pl-c1">log</span>(ia[<span class="pl-c1">42</span>]);  <span
                class="pl-c"><span class="pl-c">//</span> 314159</span></pre>
    </div>
    <p>上面代码中，主线程的<code>Atomics.store</code>向 42 号位置的赋值，一定是早于 37 位置的赋值。只要 37 号位置等于 163，Worker 线程就不会终止循环，而对 37 号位置和 42
        号位置的取值，一定是在<code>Atomics.load</code>操作之后。</p>
    <p><strong>（2）Atomics.wait()，Atomics.wake()</strong></p>
    <p>
        使用<code>while</code>循环等待主线程的通知，不是很高效，如果用在主线程，就会造成卡顿，<code>Atomics</code>对象提供了<code>wait()</code>和<code>wake()</code>两个方法用于等待通知。这两个方法相当于锁内存，即在一个线程进行操作时，让其他线程休眠（建立锁），等到操作结束，再唤醒那些休眠的线程（解除锁）。
    </p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-c1">Atomics</span>.<span class="pl-en">wait</span>(sharedArray, index, value, time)</pre>
    </div>
    <p><code>Atomics.wait</code>用于当<code>sharedArray[index]</code>不等于<code>value</code>，就返回<code>not-equal</code>，否则就进入休眠，只有使用<code>Atomics.wake()</code>或者<code>time</code>毫秒以后才能唤醒。被<code>Atomics.wake()</code>唤醒时，返回<code>ok</code>，超时唤醒时返回<code>timed-out</code>。
    </p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-c1">Atomics</span>.<span class="pl-en">wake</span>(sharedArray, index, count)</pre>
    </div>
    <p><code>Atomics.wake</code>用于唤醒<code>count</code>数目在<code>sharedArray[index]</code>位置休眠的线程，让它继续往下运行。</p>
    <p>下面请看一个例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 线程一</span>
<span class="pl-en">console</span>.<span class="pl-c1">log</span>(ia[<span class="pl-c1">37</span>]);  <span
                class="pl-c"><span class="pl-c">//</span> 163</span>
<span class="pl-c1">Atomics</span>.<span class="pl-en">store</span>(ia, <span class="pl-c1">37</span>, <span
                class="pl-c1">123456</span>);
<span class="pl-c1">Atomics</span>.<span class="pl-en">wake</span>(ia, <span class="pl-c1">37</span>, <span
                class="pl-c1">1</span>);

<span class="pl-c"><span class="pl-c">//</span> 线程二</span>
<span class="pl-c1">Atomics</span>.<span class="pl-en">wait</span>(ia, <span class="pl-c1">37</span>, <span
                class="pl-c1">163</span>);
<span class="pl-en">console</span>.<span class="pl-c1">log</span>(ia[<span class="pl-c1">37</span>]);  <span
                class="pl-c"><span class="pl-c">//</span> 123456</span></pre>
    </div>
    <p>上面代码中，共享内存视图<code>ia</code>的第 37
        号位置，原来的值是<code>163</code>。进程二使用<code>Atomics.wait()</code>方法，指定只要<code>ia[37]</code>等于<code>163</code>，就进入休眠状态。进程一使用<code>Atomics.store()</code>方法，将<code>123456</code>放入<code>ia[37]</code>，然后使用<code>Atomics.wake()</code>方法将监视<code>ia[37]</code>的休眠线程唤醒。
    </p>
    <p>另外，基于<code>wait</code>和<code>wake</code>这两个方法的锁内存实现，可以看 Lars T Hansen 的 <a
            href="https://github.com/lars-t-hansen/js-lock-and-condition">js-lock-and-condition</a> 这个库。</p>
    <p>注意，浏览器的主线程有权“拒绝”休眠，这是为了防止用户失去响应。</p>
    <p><strong>（3）运算方法</strong></p>
    <p>共享内存上面的某些运算是不能被打断的，即不能在运算过程中，让其他线程改写内存上面的值。Atomics 对象提供了一些运算方法，防止数据被改写。</p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-c1">Atomics</span>.<span class="pl-c1">add</span>(sharedArray, index, value)</pre>
    </div>
    <p><code>Atomics.add</code>用于将<code>value</code>加到<code>sharedArray[index]</code>，返回<code>sharedArray[index]</code>旧的值。
    </p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-c1">Atomics</span>.<span class="pl-c1">sub</span>(sharedArray, index, value)</pre>
    </div>
    <p><code>Atomics.sub</code>用于将<code>value</code>从<code>sharedArray[index]</code>减去，返回<code>sharedArray[index]</code>旧的值。
    </p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-c1">Atomics</span>.<span class="pl-en">and</span>(sharedArray, index, value)</pre>
    </div>
    <p><code>Atomics.and</code>用于将<code>value</code>与<code>sharedArray[index]</code>进行位运算<code>and</code>，放入<code>sharedArray[index]</code>，并返回旧的值。
    </p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-c1">Atomics</span>.<span class="pl-en">or</span>(sharedArray, index, value)</pre>
    </div>
    <p><code>Atomics.or</code>用于将<code>value</code>与<code>sharedArray[index]</code>进行位运算<code>or</code>，放入<code>sharedArray[index]</code>，并返回旧的值。
    </p>
    <div class="highlight highlight-source-js">
        <pre><span class="pl-c1">Atomics</span>.<span class="pl-en">xor</span>(sharedArray, index, value)</pre>
    </div>
    <p><code>Atomic.xor</code>用于将<code>vaule</code>与<code>sharedArray[index]</code>进行位运算<code>xor</code>，放入<code>sharedArray[index]</code>，并返回旧的值。
    </p>
    <p><strong>（4）其他方法</strong></p>
    <p><code>Atomics</code>对象还有以下方法。</p>
    <ul>
        <li><code>Atomics.compareExchange(sharedArray, index, oldval, newval)</code>：如果<code>sharedArray[index]</code>等于<code>oldval</code>，就写入<code>newval</code>，返回<code>oldval</code>。
        </li>
        <li><code>Atomics.exchange(sharedArray, index, value)</code>：设置<code>sharedArray[index]</code>的值，返回旧的值。</li>
        <li>
            <code>Atomics.isLockFree(size)</code>：返回一个布尔值，表示<code>Atomics</code>对象是否可以处理某个<code>size</code>的内存锁定。如果返回<code>false</code>，应用程序就需要自己来实现锁定。
        </li>
    </ul>
    <p><code>Atomics.compareExchange</code>的一个用途是，从 SharedArrayBuffer 读取一个值，然后对该值进行某个操作，操作结束以后，检查一下 SharedArrayBuffer
        里面原来那个值是否发生变化（即被其他线程改写过）。如果没有改写过，就将它写回原来的位置，否则读取新的值，再重头进行一次操作。</p>
</div>
</body>
</html>
